const express = require('express')
const app = express()
const cors = require('cors')
const joi = require('joi')

app.use(cors())
app.use(express.urlencoded({ extended: false }))
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())


//使用express.static内置中间件，可以进行静态资源托管，可以用tmp_uploads下的图片读取
app.use('/tmp_uploads', express.static('tmp_uploads'))

// 导入配置文件
const config = require('./config')

// 解析 token 的中间件
const expressJWT = require('express-jwt')

// 使用 .unless({ path: [/^\/api\//] }) 指定哪些接口不需要进行 Token 的身份认证
app.use(expressJWT({ secret: config.jwtSecretKey }).unless(
    {
        path:
            [
                '/api/login',
                '/api/reguser',
                '/api/bigscreen/rank',
                '/api/bigscreen/proportion',
                '/api/bigscreen/mapdata',
                '/api/bigscreen/vaccworld',
                '/api/bigscreen/covline',
                '/api/bigscreen/news',
                '/api/bigscreen/mortalityratechina',
                '/api/bigscreen/rank',
                '/api/bigscreen/vaccrate',
                '/api/bigscreen/citydata',
                '/api/bigscreen/usacovline',
                '/api/bigscreen/mapworlddata',
                '/api/bigscreen/worldcountdata',
                '/api/bigscreen/countryrank',
                '/api/bigscreen/vacctable',
                '/api/bigscreen/vaccworld100',
                '/api/bigscreen/vaccrateworld',
                '/api/bigscreen/vaccmapworlddata',
                '/api/bigscreen/jpcovline'
            ]
    }))


const userRouter = require('./router/user');
const userManaRouter = require('./router/userMana');
const newsRouter = require('./router/news');
const vaccRouter = require('./router/vaccine');
const worldvaccRouter = require('./router/worldvacc');
const cnCitydataRouter = require('./router/cnCityCovidData');
const cncovRouter = require('./router/cncov');
const worldcovRouter = require('./router/worldcov');
const usacovRouter = require('./router/usacov');
const bigscreenRouter = require('./router/bigscreen');
const japancovRouter = require('./router/japancov');
const auscovRouter = require('./router/auscov');
const rumorsRouter = require('./router/rumors');


app.use('/api', userRouter)
app.use('/api', userManaRouter)
app.use('/api', newsRouter)
app.use('/api', vaccRouter)
app.use('/api', worldvaccRouter)
app.use('/api', cnCitydataRouter)
app.use('/api', cncovRouter)
app.use('/api', usacovRouter)
app.use('/api', worldcovRouter)
app.use('/api', japancovRouter)
app.use('/api', rumorsRouter)
app.use('/api', auscovRouter)
app.use('/api/bigscreen', bigscreenRouter)

app.use((err, req, res, next) => {
    if (err instanceof joi.ValidationError) return res.send({ status: err.status, message: err })
    return res.send({ status: 500, message: err })
})

// 启动服务器
app.listen(3007, () => {
    console.log('服务器运行于http://localhost:3007/')
})